<?php
namespace app\api\controller;
use app\common\controller\CommonController;
use app\common\errcode\ApiErrCode;
use app\common\errcode\ApiErrMsg;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Loader;

class LoginController extends CommonController
{
    protected $userModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new \app\api\model\UserModel();
    }

    /**
     * 测试方法
     */
    public function test()
    {
        try {
            
        } catch (\Exception $e) {
            \app\common\model\CommonModel::savelog(0,$e,$this->request->path());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }
    }

    /**
     * 登陆
     * @param string $username  用户名
     * @param string $password  密码
     */
    public function login()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                $validate = Loader::validate('User');
                $check = $validate->scene('login')->check($data);
                if(!$check){
                    return $this->jsonJump(ApiErrCode::PARAM_ERROR,ApiErrMsg::PARAM_ERROR.','.$validate->getError());  
                }
                $res = $this->userModel->find(trim($data['username']),trim($data['password']));
                if(empty($res)) return $this->jsonJump(ApiErrCode::LOGIN_FAIL,ApiErrMsg::LOGIN_FAIL);
                if(isset($res) && $res['company'] == '离职人员') return $this->jsonJump(ApiErrCode::LOGIN_FORBIDDEN,ApiErrMsg::LOGIN_FORBIDDEN);
                $res['jwt'] = $this->create_jwt($res);
                return $this->jsonJump(ApiErrCode::SUCCESS,ApiErrMsg::SUCCESS,$res);
            }    
        } catch (\Exception $e) {
            \app\common\model\CommonModel::recordLog('','abnormal',date('Y-m-d H:i:s'),'warning',$e->getMessage());
            return $this->jsonJump(ApiErrCode::SYSTEM_ERROR,ApiErrMsg::SYSTEM_ERROR . ',错误信息:'. $e->getMessage());
        }    
    }

    /**
     * 登录成功生成jwt
     * @param array info 信息
     */
    protected function create_jwt($info){
        $key = Config('api_key'); //jwt的签发密钥，验证token的时候需要用到
        $token = array(
            "userinfo" => $info,
            "iss" => "",//签发组织
            "aud" => "",//签发作者
            "iat" => time(),
            "nbf" => time(),
            "exp" => time() + 7*24*3600
        );
        $jwt = JWT::encode($token, $key, 'HS256');
        return $jwt;
    }
    
}

